from flask import Flask, request, jsonify
import torch
from PIL import Image
import io
import os
from flask_cors import CORS  # 允许跨域

app = Flask(__name__)
CORS(app)  # 启用跨域请求
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)

@app.route('/detect', methods=['POST'])
def detect():
    if 'image' not in request.files:
        return jsonify({'error': 'No image uploaded'}), 400

    file = request.files['image']
    image = Image.open(file.stream).convert("RGB")

    results = model(image)
    detections = results.pandas().xyxy[0].to_dict(orient="records")  # 返回列表形式
    return jsonify(detections)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)    